/*
 * @Author: zhangyang
 * @Date: 2022-06-23 16:37:42
 * @LastEditTime: 2022-06-23 19:43:38
 * @Description:
 */
import { useContext } from '@modern-js/runtime/server';
import type { CreateMenuItem } from 'api/typings/app/init';

export const post = async () => {
  const ctx = useContext();

  const {
    parentId: pid = 0,
    name = '',
    title = '',
    icon = 'store',
    sort = 0,
    component = '/',
  } = ctx.request.body as CreateMenuItem;

  if (component && !component.startsWith('/')) {
    return ctx.helper.fail({ msg: '路径不合法' });
  }

  try {
    const { username, nickname } = ctx.decode;
    await ctx.service.menu.create({
      name,
      title,
      icon,
      sort,
      component,
      pid: Number(pid),
      creator: nickname || username,
    });
    return ctx.helper.success();
  } catch (error) {
    return ctx.helper.fail({ msg: (error as Error).message });
  }
};
